package memory.net;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.io.IOException;

import memory.*;
import javax.swing.*;


@SuppressWarnings("serial")
public class ClientWindow extends JFrame implements ActionListener {
	
	private DiscoverGames herde;
	
	private DefaultListModel listModel = new DefaultListModel();
	private JList list = new JList(listModel);
	private JScrollPane sp = new JScrollPane(list);
	private JPanel p = new JPanel();
	private JLabel nameLabel = new JLabel("Player name");
	private JTextField nameField = new JTextField("",10);
	private JButton findButton = new JButton("Find games");
	private JButton joinButton = new JButton("Join game");
	private JButton cancelButton = new JButton("Cancel");
	
	public MainWindow mwRef;
	
	public ClientWindow(MainWindow mw) {
		
		mwRef = mw;
		
		//mwRef.setEnabled(false);
		
		setLocationRelativeTo(mw);
		setTitle("Available games");
		add(sp, BorderLayout.CENTER);
		add(p,BorderLayout.SOUTH);
		p.add(nameLabel);
		p.add(nameField);
		p.add(findButton);
		p.add(joinButton);
		p.add(cancelButton);
		findButton.addActionListener(this);
		joinButton.addActionListener(this);
		cancelButton.addActionListener(this);
		//joinButton.setEnabled(false);
		
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		p.setPreferredSize(new Dimension(200,90));
		setSize(300,250);
		setVisible(true);
		setResizable(false);
		
	}

	
	
	public void actionPerformed(ActionEvent e) {
		
		if (e.getSource() == findButton) {
		
			listModel.clear();
			listModel.addElement("Searching...");
			
			try {
				herde = new DiscoverGames("225.231.123.56",9999);
				herde.searchGames();
			}
			catch(IOException e2 ) {
				JOptionPane.showMessageDialog(this, "Something bad happend, not connected to a network??", "Error", JOptionPane.ERROR_MESSAGE);
			}
			
			listModel.clear();
			
			for (String s : herde.getGameNames()) {
				listModel.addElement(s);
			}
		
		}

		else if (e.getSource() == joinButton) {
			if (nameField.getText().length() == 0) {
				JOptionPane.showMessageDialog(this, "Please enter a player name!");
			}
			else {		
				if (list.getSelectedIndex() == -1) {
					String address = JOptionPane.showInputDialog("Enter address");
					String input = JOptionPane.showInputDialog("Enter port");
					int port = Integer.parseInt(input);
					new ClientLobby(this ,address, port, nameField.getText());
				}			
				else {
					String[] gameInfo = herde.getGameInfo(list.getSelectedIndex());
	
					new ClientLobby(this , gameInfo[1], Integer.parseInt(gameInfo[2]),nameField.getText());			
				}
			}

		}
		
		else if (e.getSource() == cancelButton) {
			mwRef.setEnabled(true);
			dispose();
		}
		//herde.getGameInfo(nr);
	}
}